import {createSlice} from '@reduxjs/toolkit';
import instance from '../../utils/request';

//创建slice对象
let todoSlice = createSlice({
  name: 'todo',
  initialState: [],
  reducers: {
    init: (state, action) => {
      return action.payload;
    },
    add: (state, action) => {
      //更新状态
      state.push(action.payload);
    }
  }
});

//获取 action creator
// add([1,2,3]) => {type: 'todo/add', payload: [1,2,3]}
let {init, add} = todoSlice.actions;

//获取 reducer
export default todoSlice.reducer;

//定义异步的 action creator
export let asyncGetTodos = () => {
  return async dispatch => {
    //请求获取数据
    let result = await instance.get('/todos');
    //更新 redux 的状态
    dispatch(init(result));
  }
}

//异步的action creator
export let asyncAddTodo = (title) => {
  return async (dispatch) => {
    //发送请求
    let result = await instance.post('/todos', {title: title, done: false});
    //更新 redux 状态
    dispatch(add(result));
  }
}
